package com.loongxun.playwithyou.ui.fragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.loongxun.playwithyou.ApiInterface;
import com.loongxun.playwithyou.R;
import com.loongxun.playwithyou.bean.Order;
import com.loongxun.playwithyou.bean.SendRequest;
import com.loongxun.playwithyou.network.MyHttpClientRespenseHandler;
import com.loongxun.playwithyou.network.nHttpClient;
import com.loongxun.playwithyou.ui.adapter.OrderAdapter;
import com.loongxun.playwithyou.util.ToastView;
import com.loongxun.playwithyou.view.pullableview.MyListener;
import com.loongxun.playwithyou.view.pullableview.PullToRefreshLayout;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Created by Administrator on 2017/7/26.
 */
public class MemberOrderFragment extends Fragment /*implements PullToRefreshSwipeMenuListView.IXListViewListener*/{

    private View view;
    private Context context;
    private SharedPreferences share;
    private SharedPreferences.Editor editor;
    private SendRequest send;
    private String member_id;
    private int pageNo = 1;
    private boolean isPageNoMore = false;
    private List<Order> orders = new ArrayList<>();

//    private PullToRefreshSwipeMenuListView lv_member_list;
//    private Handler mHandler;
    private ListView listView;
    private PullToRefreshLayout ptrl;
    private boolean isFirstIn = true;
    private TextView loadstate_tv;
    private OrderAdapter mAdapter;

    public MemberOrderFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//        super.onCreateView(inflater, container, savedInstanceState);
        view = inflater.inflate(R.layout.fragment_member_order_list, container, false);

        context = getActivity();
        share = context.getSharedPreferences("userInfo", 0);
        editor = share.edit();//获取编辑器

//        lv_member_list = (PullToRefreshSwipeMenuListView) view.findViewById(R.id.lv_member_list);
//        lv_member_list.setPullRefreshEnable(true);
//        lv_member_list.setPullLoadEnable(true);
//        lv_member_list.setXListViewListener(this);
//        mHandler = new Handler();

        ptrl = ((PullToRefreshLayout) view.findViewById(R.id.refresh_view));
        loadstate_tv = (TextView) view.findViewById(R.id.loadstate_tv);
//        ptrl.setOnRefreshListener(new MyListener());
        ptrl.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(final PullToRefreshLayout pullToRefreshLayout) {
                // 下拉刷新操作
                new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        pageNo = 1;
                        initData(pageNo);
                        // 千万别忘了告诉控件刷新完毕了哦！
                        pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                    }
                }.sendEmptyMessageDelayed(0, 3000);
            }

            @Override
            public void onLoadMore(final PullToRefreshLayout pullToRefreshLayout) {
                // 下拉刷新操作
                new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        if (isPageNoMore) {
                            pageNo = pageNo + 1;
                            initData(pageNo);
                        }else {
                            loadstate_tv.setText("已加载全部数据");
                        }
                        // 千万别忘了告诉控件刷新完毕了哦！
                        pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                    }
                }.sendEmptyMessageDelayed(0, 3000);

            }
        });
        listView = (ListView) view.findViewById(R.id.content_view);

        member_id = share.getString("member_id", "");
        initData(pageNo);
        ptrl.autoRefresh();
        return view;
    }

    private void initData(int pageNo) {
        try {
            send = new SendRequest();
            send.memberId = member_id;
            send.pageNo = pageNo;
            //判断此会员是否为陪玩人员
            nHttpClient.getAll(ApiInterface.ORDER_LIST, send.toOrderMemberJson().toString(), orderMemberHandler);
        }catch (Exception e){
            ToastView toast = new ToastView(context, "参数错误");
            toast.show();
        }
    }

//    @Override
//    public void onWindowFocusChanged(boolean hasFocus) {
//        super.onWindowFocusChanged(hasFocus);
//        // 第一次进入自动刷新
//        if (isFirstIn) {
//            ptrl.autoRefresh();
//            isFirstIn = false;
//        }
//    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private MyHttpClientRespenseHandler orderMemberHandler = new MyHttpClientRespenseHandler() {

        @Override
        public void success(JSONObject json) {
            Integer succeed = json.optJSONObject("status").optInt("succeed", 0);
            JSONArray itemArray;
            if (succeed == 1) {
                try {
                    itemArray = json.getJSONObject("data").getJSONArray("orderList");
                    if (pageNo == 1) {
                        orders.clear();
                    }
                    for(int i = 0;i < itemArray.length();i++) {
                        JSONObject subItemObject = itemArray.getJSONObject(i);
                        Order order = new Order();
                        order.setHours_num(subItemObject.getInt("hours_num"));
                        order.setOrder_no(subItemObject.getString("order_no"));
                        order.setPlay_start_time(subItemObject.getString("play_start_time"));
                        order.setOrder_state(subItemObject.getInt("order_state"));
                        orders.add(order);
                    }
                    isPageNoMore = json.getJSONObject("data").getBoolean("isPageNoMore");
//                    lv_member_list.setPullLoadEnable(isPageNoMore);
                    listView.setAdapter(mAdapter);
                    if (mAdapter == null) {
                        mAdapter = new OrderAdapter(context,orders);
//                        lv_member_list.setAdapter(mAdapter);
                    }else {
                        mAdapter.setList(orders);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else {
                String error_desc = json.optJSONObject("status").optString("error_desc");
                new ToastView(context, error_desc).show();
            }
        }

        @Override
        public void faile(String json) {
            new ToastView(context, json).show();
        }
    };

//    @Override
//    public void onRefresh() {
//        mHandler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                SimpleDateFormat df = new SimpleDateFormat("MM-dd HH:mm", Locale.getDefault());
//                RefreshTime.setRefreshTime(getActivity().getApplicationContext(), df.format(new Date()));
//                pageNo = 1;
//                initData(pageNo);
//                lv_member_list.setRefreshTime(RefreshTime.getRefreshTime(getActivity().getApplicationContext()));
//                lv_member_list.stopRefresh();
//                lv_member_list.stopLoadMore();
//            }
//        }, 100);
//    }
//
//    @Override
//    public void onLoadMore() {
//        pageNo = pageNo + 1;
//        initData(pageNo);
//        new ToastView(context, pageNo+"").show();
//    }
}
